package com.gem.talkbase.activity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

import java.util.List;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.XMPPException;
import com.gem.talkbase.R;
import com.gem.talkbase.adapter.ChatMsg_Adapter;
import com.gem.talkbase.bean.ChatMsg;
import com.gem.talkbase.bean.Firend;
import com.gem.talkbase.client.Client;
import com.gem.talkbase.fragment.Fragment_message;
import com.gem.talkbase.service.JSON_friend;
import com.gem.talkbase.util.MessageDB;
import com.gem.talkbase.util.MyDate;
import com.gem.talkbase.util.XmppTool;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Chat_Activity  extends MyActivity {

	private ChatMsg_Adapter adapter;
	private List<ChatMsg> listMsg = new ArrayList<ChatMsg>();
	private MessageDB messageDB;//存消息的本地数据库  
	private EditText msgText;
    private ListView listview;
    private TextView user_id;
	private String pUSERID,friendimage ,friendname,pUSERID1;
	private String myID,friendid ;
	private String requestPath=Client.Firend_unick_image;
	private List<Firend> list; 
	private List<Firend> list1; 
	SharedPreferences preference;
	 
	/**
	 * 加载消息历史，从数据库中读出  
	 */  
	public void initData() {
		if((getIntent().getStringExtra("friendid"))!=null){
		System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
		  System.out.println(pUSERID+"________________++++_______");
				List<ChatMsg> list = messageDB.getMsg(pUSERID);
				  System.out.println("________________++++_______");
				if (list.size() > 0) {
					for (ChatMsg entity : list){
						listMsg.add(entity);
					}
					Collections.reverse(listMsg);
				}
				 System.out.println("111111111111111111111111111111111111111");
				 adapter = new ChatMsg_Adapter(this, listMsg ,friendname,friendimage);
				 listview.setAdapter(adapter);
			     System.out.println("2222222222222222222222222222222222222222");
				 listview.setSelection(adapter.getCount() - 1); 
		   }
	  }
//	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		messageDB.close();
	}
	public void fun(String fname,String fimage,String fid ){
		List<ChatMsg> list = messageDB.getMsg(fid);
		  System.out.println("________________++++_______");
		if (list.size() > 0) {   
			System.out.println("我三十九卅的说反话哈市地方哈市地方");
			for (ChatMsg entity : list){
				listMsg.add(entity);
			}
			Collections.reverse(listMsg);
		}
		 user_id.setText(fname);
		 System.out.println(listMsg.size()+"111111111111111111111111111111111111111");  
		 adapter = new ChatMsg_Adapter(this, listMsg ,fname,fimage);
		 listview.setAdapter(adapter);
	     System.out.println("2222222222222222222222222222222222222222");
		 listview.setSelection(adapter.getCount() - 1); 
	}   
	@Override
	public void onCreate(Bundle savedInstanceState) {  
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.formclient);
		messageDB = new MessageDB(this);
		//好友id
	    this.pUSERID = getIntent().getStringExtra("friendid");
	    
	        listview = (ListView) findViewById(R.id.formclient_listview);
	  		listview.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
	  		msgText = (EditText) findViewById(R.id.formclient_text);
	        user_id=(TextView)findViewById(R.id.user_id);
	    	
	 
	    if(pUSERID==null){
	    	 Intent intent = getIntent();  
	    	 pUSERID = intent.getStringExtra("user_name");//好友id
	    	 System.out.println(intent.getStringExtra("user_name")+"========pUsERID");
	    	 if (pUSERID!=null) {
	    		 fun1(pUSERID);	
			}
	    	
	    	 System.out.println(pUSERID+"0000000000000000000000000000");
	    	 
	    	 if (pUSERID==null) {
	    		 Intent intent2 = getIntent();  
		    	 pUSERID = intent2.getStringExtra("friend_id");//好友id
		    	 fun1(pUSERID);	
			}
	    	 
//	    	 Intent intent2=getIntent();    	
//	    	 String  friend_id=intent2.getStringExtra("friend_id");
//	    	 String  friend_unick=intent2.getStringExtra("friend_unick");
//	    	 String  friend_image=intent2.getStringExtra("friend_image");
//	    	 System.out.println(friend_id+"PPPPPPP"+friend_image+"pppppp"+friend_unick);
//	    	 fun(friend_unick, friend_image, friend_id);
    	
	      }else {	
		    
	    	  //好友头像  
		    friendimage=getIntent().getStringExtra("friendimage");
		    //好友昵称
		    friendname=getIntent().getStringExtra("friendname");
		    System.out.println("普通friendimage===="+friendimage);
	        System.out.println("普通friendname===="+friendname);
		}
	    System.out.println("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM");
//	    //好友头像
//	    friendimage=getIntent().getStringExtra("friendimage");
//	    //好友昵称
//	    friendname=getIntent().getStringExtra("friendname");
	    
	    //登录者id  
		this.myID = getIntent().getStringExtra("name");
		System.out.println(pUSERID+"===----"+myID);
			
	 	 
		  initData();
		
        user_id.setText(friendname);
				
		ChatManager cm = XmppTool.getConnection().getChatManager();
	  
        final Chat newchat1 = cm.createChat(pUSERID+ "@10.10.0.13", null);//固定格式：@+服务器名称



		//点击发送按钮发送消息
		Button btsend = (Button) findViewById(R.id.formclient_btsend);
		btsend.setOnClickListener(new OnClickListener() {  
			@Override
			public void onClick(View v) {
				 	
				//按发送按钮=========================
				String msg = msgText.getText().toString();
		
				if(msg.length() > 0){
					ChatMsg entity = new ChatMsg();
					 
					entity.setUserid(myID);
					entity.setMsg(msg);
					entity.setDate(MyDate.getDateEN());
					entity.setFrom("OUT");
					messageDB.saveMsg(pUSERID, entity);
					//listMsg.add(entity);	
					listMsg.add(new ChatMsg(myID, msg, MyDate.getDateEN(), "OUT"));	
					adapter.notifyDataSetChanged();//listView动态加载
					listview.setSelection(listview.getCount() - 1);//显示聊天最后一行。
					try {  
						
						System.out.println("============"+msg);
      
						newchat1.sendMessage(msg);

					} 
					catch (XMPPException e)
					{
						e.printStackTrace();
					}
				}
				else
				{
					Toast.makeText(Chat_Activity.this, "消息不能为空", Toast.LENGTH_SHORT).show();
				}
				
				msgText.setText("");
			}
		});  
			}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) 
		{
							  
			switch (msg.what) {
			case 1:
			
				String[] args = (String[]) msg.obj;
				System.out.println(args[0]+"#########"+args[1]+"####"+args[2]+"#####"+args[3]);
				listMsg.add(new ChatMsg(args[0], args[1], args[2], args[3]));
				adapter.notifyDataSetChanged();
				listview.setSelection(listview.getCount() - 1);//显示聊天最后一行。
				break;			

			default:
				break;
			}
		};  
	};
	public void fun1(final String username){
		AjaxParams params = new AjaxParams();
		params.put("username", username);
		System.out.println(username+"==================fun1===============================");
		FinalHttp fh = new FinalHttp();
		fh.post(requestPath, params, new AjaxCallBack<String>() {
			@Override
			public void onFailure(Throwable t, String strMsg) {
				System.out.println("加载失败！！！");
				super.onFailure(t, strMsg);
			}
			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				System.out.println("正在加载！！！");
				super.onLoading(count, current);
			}
			
			@Override  
			public void onSuccess(String jsonString) {
	 			super.onSuccess(jsonString); 
				System.out.println(jsonString.toString()+"***********************");
				list=new ArrayList<Firend>();
				JSON_friend json_friend= new JSON_friend();
				list= json_friend.fun(jsonString);
			    Iterator<Firend> iterator=list.iterator();
					Firend firend=new Firend();
					String name =null;
					String userimage=null;   
					while(iterator.hasNext()){ 
						firend=iterator.next(); 
					    name=firend.getUsername();
					    userimage=firend.getUimage();	
					    System.out.println(name+"IIIIIIIIIIIIIIIIIIIIIIII"+userimage);
					} 
					 user_id.setText(name);
					    	 friendimage=userimage;
					    	 friendname=name;
					    	 Client.FriendName=friendname;
					    	 Client.FriendHeadimage=friendimage;
					    	 List<ChatMsg> list = messageDB.getMsg(pUSERID);
							  System.out.println("________________++++_______");
							if (list.size() > 0) {
								for (ChatMsg entity : list) {
									listMsg.add(entity);
								}
								Collections.reverse(listMsg);
							}
							 System.out.println("111111111111111111111111111111111111111");
							 adapter = new ChatMsg_Adapter(Chat_Activity.this, listMsg ,friendname,friendimage);
							 listview.setAdapter(adapter);
						     System.out.println("2222222222222222222222222222222222222222");
							 listview.setSelection(adapter.getCount() - 1); 
	 
					    	 System.out.println("通知friendimage===="+friendimage);
					    	 System.out.println("通知friendname===="+friendname);
					  
			}
		});
	}
	
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		Intent intent=new Intent(Chat_Activity.this,MainActivity.class);
		startActivity(intent);
		finish();
	}
	
	@Override
	public void getMessage(ChatMsg msg) {
		System.out.println(msg+"HHHHHHHHHHHHHHHHHHHHHHHHHHH");
		if(msg.getUserid().equals(pUSERID)){
			System.out.println(msg.getUserid()+"KKKKKKKKKKKKKKKKKKKKK");
			listMsg .add(msg);
			adapter.notifyDataSetChanged();
			listview.setSelection(listview.getCount() - 1);
		} else {
//			Toast.makeText(Chat_Activity.this,
//					"您有新的消息来自：" + msg.getUserid() + ":" + msg.getMsg(),
//					Toast.LENGTH_LONG).show();		
			 fun1(msg.getUserid() ,msg.getMsg() )  ;
//			 Fragment_message fragment_message=new Fragment_message();
//			 Bundle bundle=new Bundle();
//			 bundle.putString("friendid", msg.getUserid());//绑定登录id号
//			 bundle.putString("date", msg.getDate());
//			 bundle.putString("msg", msg.getMsg());
//			 fragment_message.setArguments(bundle);
		}
		
	}
	
	 public void fun1(String name ,String mes){
   	  
   	  
   	  System.out.println("######################################################");
   	
   	  NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
 		   
 		  //得到通知      notificaString 是快速显示在屏幕最上方的，然后很快消失
 	      Notification notification = new Notification( R.drawable.talknotification, name+"发来一条消息" , System.currentTimeMillis()) ;
 	    
   	    //点击通知的内容 ，跳转到Myactivity
   	  Intent notificationIntent = new Intent(Chat_Activity.this, Chat_Activity.class);
 //   	notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//刷新 
      PendingIntent contentIntent = PendingIntent.getActivity(Chat_Activity.this, 0, notificationIntent, 0)  ;
         
         //如果点击通知后不做任何操作 ，则把contentIntent设置为null
   	  notification.setLatestEventInfo(Chat_Activity.this,name+"发来一条消息", mes , contentIntent)  ;  
   	  notification.flags  = Notification.FLAG_AUTO_CANCEL ;          //点击会自动消失
   	   
   	  notification.defaults = notification.DEFAULT_SOUND ;        
   	 //DEFAULT_SOUND 通知来的时候，会调用系统的铃声，测试的结果是手机短信声音
   	  
   	  //清除原来的通知
   	  notificationManager.cancel(0);
   	  notificationManager.notify( 0 , notification) ;	  
    
     }
 
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//	    if (keyCode == KeyEvent.KEYCODE_BACK) {
//	        moveTaskToBack(true);//true对任何Activity都适用
//	        return true;
//	    }
//	    return super.onKeyDown(keyCode, event);
//	}
//	@Override
//	public void onBackPressed()
//	{
//		super.onBackPressed();
////		XmppTool.closeConnection();
////		System.exit(0);
////		android.os.Process.killProcess(android.os.Process.myPid());
//	}
	



}